﻿using ScratchNet.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace ScratchNet
{

    public class GetInputValueExpression : Expression
    {
        private static IOBoardContent _ioBoardContent = new IOBoardContent();
        private static List<string> inPutValues = new List<string>();
        public override string ReturnType => "any";
        public string InPutValue { get; set; }

        public GetInputValueExpression()
        {
            
        }

        public GetInputValueExpression(IOBoardContent ioBoardContent)
        {
            _ioBoardContent = ioBoardContent;
            // 初始化个数
            if (!inPutValues.Any() && ioBoardContent.IOTypeCountDict.TryGetValue(LinkIOTypeEmParaDLL.DIn_HD, out var inputs))
            {
                for (int i = 1; i <= inputs.Count; i++)
                {
                    inPutValues.Add($"input{i}");
                }
            }
            InPutValue = inPutValues.FirstOrDefault();

        }
        protected override Completion ExecuteImpl(ExecutionEnvironment enviroment)
        {
            if (string.IsNullOrEmpty(InPutValue))
            {
                return Completion.Exception(Properties.Language.NullException, this);
            }
            return new Completion(true, GetConvertStr());
        }
        public override Descriptor Descriptor
        {
            get
            {
                Descriptor desc = new Descriptor();
                desc.Add(new TextItemDescriptor(this, "EDS2000 获取 DI", true));
                desc.Add(new SelectionItemDescriptor(this, "InPutValue", inPutValues, inPutValues));

                return desc;
            }
        }

        public override string Type
        {
            get { return "GetInputValueExpression"; }
        }

        private string GetConvertStr()
        {
            int index = UtilityExtension.GetNumberByString(InPutValue) - 1;
            if (index < 0 || index >= _ioBoardContent.IOTypeCountDict[LinkIOTypeEmParaDLL.DIn_HD].Count)
            {
                return string.Empty;
            }
            string plcPinName = _ioBoardContent.IOTypeCountDict[LinkIOTypeEmParaDLL.DIn_HD][index].plcPinName;
            return $"ComTaskManager.PLC62541ConnectionClient.ReadPlcGlobalVariable<bool>(\"{plcPinName}\")";
        }
    }
}
